// ==UserScript==
// @name         github md文件图片
// @namespace    http://tampermonkey.net/
// @version      2025-01-06
// @description  try to take over the world!
// @author       You
// @match        https://github.com/modelscope/modelscope-classroom/blob/main/LLM-tutorial/C.%E6%8F%90%E7%A4%BA%E8%AF%8D%E5%B7%A5%E7%A8%8B-prompt%20engineering.md?plain=1
// @icon         https://www.google.com/s2/favicons?sz=64&domain=github.com
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM.setValue
// @grant        GM.getValue
// ==/UserScript==

(function() {
    'use strict';
    /* 匹配 github.com 加 plain=1末尾 地址*/
    window.addEventListener('load', addPanel);
    const markdownEle = document.querySelector('#read-only-cursor-text-area');

    // Your code here...
})();
/** 弹出居中窗口 */
function popupCenter(url, title = '_blank', w, h) {
    // 检查参数有效性
    if (!url || typeof url !== 'string') {
        console.error('Invalid URL provided');
        return null;
    }

    // 设置默认标题和窗口尺寸
    title = title || '_blank';
    w = Math.min(w, screen.availWidth);
    h = Math.min(h, screen.availHeight);

    // 计算居中位置
    let x = (screen.availWidth - w) / 2;
    let y = (screen.availHeight - h) / 2;

    // 确保窗口不会超出屏幕边界
    x = Math.max(x, 0);
    y = Math.max(y, 0);

    // 打开新窗口
    let win;
    try {
        win = window.open(url, title, `width=${w},height=${h},left=${x},top=${y}`);
        if (win) {
            win.focus();
            // let closeNewWindow =  window.addEventListener('focus', function() {
            //     win.close();
            //     window.removeEventListener('focus', closeNewWindow);
            // });
        } else {
            throw new Error('Failed to open the window');
        }
    } catch (e) {
        console.error('Error opening the window:', e);
    }

    return win;
}
function addPanel(){
    function genButton(text, foo, id, fooParams = {}){
        let b = document.createElement('button');
        b.textContent = text;
        b.style.verticalAlign = 'inherit';
        // 使用箭头函数创建闭包来保存 fooParams 并传递给 foo
        b.addEventListener('click', () => {
            foo.call(b, ...Object.values(fooParams)); // 使用 call 方法确保 this 指向按钮对象
        });
        if(id){ b.id = id };
        return b;
    }
    function changeRangeDynamics() {
        const value = parseInt(this.value, 10);
        const roundedValue = Math.ceil(value / 10) * 10;
    
        targetAmountGlobal = roundedValue;
        // 只能通过 DOM 方法改变
        document.querySelector('#swal-range > output').textContent = roundedValue;
    }
    async function openPanelFunc(){
        isLoadEnd = false;
        //重置值
        targetAmountGlobal = 100;
        var swalRangeValue = 100;
        let checkInterval;
        const { value: formValues } = await Swal.fire({
            title: "Customization",
            allowOutsideClick: false,
            allowEscapeKey: false,
            allowEnterKey: false,
            showCancelButton: true,
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            //class="swal2-range" swalalert框架可能会对其有特殊处理，导致其内标签的id声明失效
            html: `
              <input id="swal-input1" placeholder='正则表达式过滤' class="swal2-input">
              <div class="swal2-range" id="swal-range" style="display: flex;">
                <input type="range" min="0" max="500" step="10" value="100">
                <output>${swalRangeValue}</output>
              </div>
              <div class="swal2-radio">
                <input type="radio" id="option1" name="options" value="option1" checked>
                <label for="option1"><span class="swal2-label" checked>热门评论</span></label>
                <input type="radio" id="option2" name="options" value="option2">
                <label for="option2"><span class="swal2-label">评论IP</span></label>
              </div>
              <select id="swal2-select" class="swal2-select">
                <option value="" disabled="">选择分本分析引擎</option>
                <option value="wordcloudOnline">Wordcloud Online</option>
                <option value="lzlTool">LZL工具</option>
                <option value="lingJoin">NLPIR演示平台</option>
                <optgroup label="wenpipi">
                  <option value="fenxi">文本分析</option>
                  <option value="zihua">字画</option>
                  <option value="comment">差评分析</option>
                  <option value="esse">文章摘要</option>
                </optgroup>
              </select>
            `,
            footer: `<span style="color:#6a60547a">当前评论总数:${allCountPageData}</span>`,
            focusConfirm: false,
            didOpen: () => {
                //重置状态
                commentManager = new CommentManager();
                const swalRange = document.querySelector('#swal-range input');
                swalRange.addEventListener('input', changeRangeDynamics);
                document.querySelector('.swal2-radio > input[type=radio]:nth-child(1)').checked = true;
            },
            willClose: () => {
                // 在关闭前清除事件监听器以防止内存泄漏
                const swalRange = document.querySelector('#swal-range input');
                swalRange.removeEventListener('input', changeRangeDynamics);
            },
            preConfirm: () => {
                checkInterval = setInterval(() => {
                    if (isLoadEnd) {
                        // 如果 isLoadEnd 为 true，停止定时器并隐藏加载弹窗
                        clearInterval(checkInterval);//无法正常关闭定时器
                        Swal.hideLoading();
                        Swal.close(); // 关闭弹窗
                    }
                }, 200);
                return [
                    document.getElementById("swal-input1").value,
                    targetAmountGlobal,
                    document.querySelector('.swal2-radio>input[name="options"]:checked').value,
                    document.querySelector('.swal2-select').value
                ];
            }
        });
        if (formValues) {
            // Swal.fire(JSON.stringify(formValues));
            regexGlobal = formValues[0];
            targetAmountGlobal = formValues[1];
            optionGlobal = formValues[2];
            wordcloudOption = formValues[3];
            Swal.fire({
                title: '(๑¯ω¯๑)抓取中...',
                allowOutsideClick: false,
                allowEscapeKey: false,
                allowEnterKey: false,
                showConfirmButton: false,
                onBeforeOpen: () => {
                    Swal.showLoading();
                },
                willClose: () => {
                    // 确保在关闭弹窗时清除定时器
                    clearInterval(checkInterval);
                }
            });
            pageDataHandle(firstPageData, optionGlobal, targetAmountGlobal);
            generateFinalCommentManger();
        }
    }

    let myButton = genButton('comment', openPanelFunc, 'myButton');
    document.body.appendChild(myButton);

    tippy('#myButton', {
        content: '⁙ὸ‿ό⁙',
        placement: 'bottom', 
        delay: [500, 0],//延迟出现500，消失0
        duration: 300,
        arrow: true,
    });

    var css_text =`
        #myButton {
            position: fixed;
            top: 50%;
            left: -20px;/* 初始状态下左半部分隐藏 */
            transform: translateY(-50%);
            z-index: 1000; /* 确保按钮在最前面 */
            padding: 10px 24px;
            border-radius: 5px;
            cursor: pointer;
            border: 0;
            background-color: white;
            box-shadow: rgb(0 0 0 / 5%) 0 0 8px;
            letter-spacing: 1.5px;
            text-transform: uppercase;
            font-size: 9px;
            transition: all 0.5s ease;
        }
        #myButton:hover {
            left: 0%; /* 鼠标悬停时完整显示 */
            letter-spacing: 3px;
            background-color: hsl(261deg 80% 48%);
            color: hsl(0, 0%, 100%);
            box-shadow: rgb(93 24 220) 0px 7px 29px 0px;
        }
        #myButton:active {
            letter-spacing: 3px;
            background-color: hsl(261deg 80% 48%);
            color: hsl(0, 0%, 100%);
            box-shadow: rgb(93 24 220) 0px 0px 0px 0px;
            transition: 100ms;
        }
    `
    GMaddStyle(css_text);
}